package pixeleditor.ctrl.impl;

import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import common.core.Tile;
import common.ctrl.IObserver;
import common.gui.IViewable;

import pixeleditor.core.Board;
import pixeleditor.core.PaintSetup;

public class GridCtrl extends MouseAdapter implements IObserver {

	private List<IViewable> iv = new ArrayList<IViewable>();

	@Override
	public void addView(IViewable iv) {
		this.iv.add(iv);
	}


	@Override
	public void mouseClicked(MouseEvent e) {
		Point p = e.getPoint();
		PaintSetup ps = Board.getInstance().getPaintSetup();

		//Check if we will add player to the board or paint tile.
		if(ps.getAddPlayer() != 0)
			checkIfPlayerCanBeAdded(p);
		else
			paintTile(p);
	}

	
	private void checkIfPlayerCanBeAdded(Point p) {
		boolean canBeAdded = true;
		int x = p.x/10;
		int y = p.y/10;

		for(int i=0; i<6; i++) {
			for(int j=0; j<5; j++) {
				//Check so that no tiles are under a player when adding
				if(Board.getInstance().getScenery().getTiles()[y-2+i][x+j] != null)
					canBeAdded = false;
			}
		}
		
		if(canBeAdded) {
			if(Board.getInstance().getPaintSetup().getAddPlayer() == PaintSetup.PLAYER1)
				Board.getInstance().setPlayer1(new Point(x, y));
			else if(Board.getInstance().getPaintSetup().getAddPlayer() == PaintSetup.PLAYER2)
				Board.getInstance().setPlayer2(new Point(x, y));
			Board.getInstance().getPaintSetup().setAddPlayer(PaintSetup.NONE);
			for(IViewable i : iv)
				i.updateView("player");
		}
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		Point p = e.getPoint();

		if(Board.getInstance().getPaintSetup().getAddPlayer() == PaintSetup.NONE)
			paintTile(p);
	}

	private void paintTile(Point p) {
		int x = p.x/10;
		int y = p.y/10;
		PaintSetup ps = Board.getInstance().getPaintSetup();

		for(int i=0; i<ps.getSize(); i++) {
			for(int j=0; j<ps.getSize(); j++) {
				if(!checkIfPlayerIsInPaintArea(x,y))
					Board.getInstance().setTile(y+j, x+i, 
							new Tile(ps.isDestructible(), ps.getCurrentColor()));
			}
		}
		for(IViewable i : iv)
			i.updateView("player");
	}

	private boolean checkIfPlayerIsInPaintArea(int x, int y) {
		int PW = 5;
		int PH = 4;
		
		boolean bp1 = false, bp2 = false;
		//TODO not working when choosing larger brush sizes
		if(Board.getInstance().getPlayer1() != null) {
			Point p1 = Board.getInstance().getPlayer1();
			bp1 = ((y+2 >= p1.y && y <= p1.y+PH) && (x+1 >= p1.x && x <= p1.x+PW));
		}
		if(Board.getInstance().getPlayer2() != null) {
			Point p2 = Board.getInstance().getPlayer2();
			bp2 =((y+2 >= p2.y && y <= p2.y+PH) && (x+1 >= p2.x && x <= p2.x+PW));
		}

		return bp1 || bp2;

	}
}
